package com.ungao.framework.proxy;


import com.ungao.framework.annotation.Delete;
import com.ungao.framework.annotation.Insert;
import com.ungao.framework.annotation.Select;
import com.ungao.framework.annotation.Update;
import com.ungao.framework.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

public class MapperProxy implements InvocationHandler {

    private SqlSession sqlSession;

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //组装mapper缓存key-> namespace.id
        String statementKey = method.getDeclaringClass().getName() + "." + method.getName();

        //处理自定义注解Insert
        if (method.isAnnotationPresent(Insert.class)) {
            return this.sqlSession.insert(statementKey, args);
        }

        //处理自定义注解Delete
        if (method.isAnnotationPresent(Delete.class)) {
            return this.sqlSession.delete(statementKey, args);
        }

        //处理自定义注解Update
        if (method.isAnnotationPresent(Update.class)) {
            return this.sqlSession.update(statementKey, args);
        }

        //处理自定义注解Select
        if (method.isAnnotationPresent(Select.class)) {
            if (Collection.class.isAssignableFrom(method.getReturnType())) {
                return this.sqlSession.selectList(statementKey, args);
            } else {
                return this.sqlSession.selectOne(statementKey, args);
            }
        }

        //默认不做任何处理，直接放行
        return method.invoke(this, args);
    }
}
